<?php
require_once(DIR_SYSTEM . 'vendor/autoload.php'); // 你的 composer 依赖
class ControllerToolGoogleShopping extends Controller {
//    composer require google/apiclient:^2.0
//    1、确认 credentials.json 路径，建议放在 /system/ 目录。
//    2、修改 $merchantId 和 'brand' 字段为你自己的信息。
//    3、用后台管理员账户登录后，访问如下URL触发上传（需替换token）：
//    https://你的后台域名/admin/index.php?route=tool/google_shopping&user_token=XXX
//    4、上传结果会直接在页面输出，建议先只传5个，确认没报错后再批量。

    public function upload() {
        $this->response->addHeader('Content-Type: application/json; charset=utf-8');
        $this->response->addHeader('Cache-Control: no-store');

        try {
            if (!$this->user->hasPermission('modify', 'tool/google_shopping')) {
                $this->response->addHeader('HTTP/1.1 403 Forbidden');
                $this->response->setOutput(json_encode([
                    'status' => 'error',
                    'message' => '无权限操作'
                ], JSON_UNESCAPED_UNICODE));
                return;
            }

            $input = file_get_contents('php://input');
            $json  = json_decode($input, true);

            if (!isset($json['product_ids']) || !is_array($json['product_ids']) || !$json['product_ids']) {
                $this->response->addHeader('HTTP/1.1 422 Unprocessable Entity');
                $this->response->setOutput(json_encode([
                    'status' => 'error',
                    'message' => '缺少或为空的 product_ids'
                ], JSON_UNESCAPED_UNICODE));
                return;
            }

            // 可选：执行时间较长时放开限制
            @set_time_limit(300);

            // 初始化 Google Client（这里建议 try-catch）
            $client = new \Google_Client();
            $client->setAuthConfig(DIR_SYSTEM . 'credentials.json');
            $client->addScope('https://www.googleapis.com/auth/content');
            $client->useApplicationDefaultCredentials();
            $service = new \Google_Service_ShoppingContent($client);

            $merchantId = '5419773399';
            $brand = 'IrugbyStore';

            $this->load->model('catalog/product');

            $results = [];

            foreach ($json['product_ids'] as $product_id) {
                $product_info = $this->model_catalog_product->getProduct((int)$product_id);

                if (!$product_info) {
                    $results[] = [
                        'product_id' => (int)$product_id,
                        'lang'       => null,
                        'status'     => 'fail',
                        'message'    => '商品不存在'
                    ];
                    continue;
                }

                $name = $product_info['name'];
                $description = isset($product_info['description'])
                    ? strip_tags(html_entity_decode($product_info['description'], ENT_QUOTES, 'UTF-8'))
                    : '';
                $price = (string)$product_info['price'];
                $image_url = !empty($product_info['image']) ? HTTPS_CATALOG . 'image/' . $product_info['image'] : '';
                $link = HTTPS_CATALOG . 'index.php?route=product/product&product_id=' . (int)$product_id;

                // 英文
                $product_en = new \Google_Service_ShoppingContent_Product([
                    'offerId'         => (string)$product_id . '-en',
                    'title'           => $name,
                    'description'     => $description,
                    'link'            => $link,
                    'imageLink'       => $image_url,
                    'contentLanguage' => 'en',
                    'targetCountry'   => 'US',
                    'channel'         => 'online',
                    'availability'    => 'in stock',
                    'condition'       => 'new',
                    'price'           => ['value' => $price, 'currency' => 'USD'],
                    'brand'           => $brand
                ]);

                // 法文（示例里还是用英文内容，生产建议提供法文）
                $product_fr = new \Google_Service_ShoppingContent_Product([
                    'offerId'         => (string)$product_id . '-fr',
                    'title'           => $name,
                    'description'     => $description,
                    'link'            => $link,
                    'imageLink'       => $image_url,
                    'contentLanguage' => 'fr',
                    'targetCountry'   => 'FR',
                    'channel'         => 'online',
                    'availability'    => 'in stock',
                    'condition'       => 'new',
                    'price'           => ['value' => $price, 'currency' => 'EUR'],
                    'brand'           => $brand
                ]);

                // 上传英语
                try {
                    $service->products->insert($merchantId, $product_en);
                    $results[] = [
                        'product_id' => (int)$product_id,
                        'lang'       => 'en',
                        'status'     => 'success',
                        'message'    => '上传成功（英文）'
                    ];
                } catch (\Exception $e) {
                    $results[] = [
                        'product_id' => (int)$product_id,
                        'lang'       => 'en',
                        'status'     => 'fail',
                        'message'    => $e->getMessage()
                    ];
                }

                // 上传法文
                try {
                    $service->products->insert($merchantId, $product_fr);
                    $results[] = [
                        'product_id' => (int)$product_id,
                        'lang'       => 'fr',
                        'status'     => 'success',
                        'message'    => '上传成功（法文）'
                    ];
                } catch (\Exception $e) {
                    $results[] = [
                        'product_id' => (int)$product_id,
                        'lang'       => 'fr',
                        'status'     => 'fail',
                        'message'    => $e->getMessage()
                    ];
                }
            }

            // 200 + 汇总
            $this->response->setOutput(json_encode([
                'status'  => 'done',
                'results' => $results
            ], JSON_UNESCAPED_UNICODE));

        } catch (\Throwable $e) {
            // 500 兜底
            $this->log->write('Google Shopping 上传异常：' . $e->getMessage());
            $this->response->addHeader('HTTP/1.1 500 Internal Server Error');
            $this->response->setOutput(json_encode([
                'status'  => 'error',
                'message' => '服务器异常：' . $e->getMessage()
            ], JSON_UNESCAPED_UNICODE));
        }
    }


    public function index() {
        $this->response->setOutput('请通过 AJAX 调用 upload 接口上传商品。');
//        // 权限校验（可选）
//        if (!$this->user->hasPermission('modify', 'tool/google_shopping')) {
//            $this->session->data['error_warning'] = '无权限操作';
//            $this->response->redirect($this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token'], true));
//            return;
//        }
//
//        // 初始化 Google API 客户端
//        $client = new \Google_Client();
//        $client->setAuthConfig(DIR_SYSTEM . 'credentials.json'); // 密钥文件路径
//        $client->addScope('https://www.googleapis.com/auth/content');
//        $client->useApplicationDefaultCredentials();
//        $service = new \Google_Service_ShoppingContent($client);
//
//        // 你的 Merchant Center ID
//        $merchantId = 'YOUR_MERCHANT_ID';
//
//        // 取商品数据
//        $this->load->model('catalog/product');
//        $products = $this->model_catalog_product->getProducts();
//
//        // 为安全起见，建议先只上传前5个
//        $products = array_slice($products, 0, 5);
//
//        $result_log = [];
//
//        foreach ($products as $p) {
//            $product_id = $p['product_id'];
//            $name = $p['name'];
//            // 获取商品描述
//            $product_info = $this->model_catalog_product->getProduct($product_id);
//            $description = isset($product_info['description']) ? strip_tags(html_entity_decode($product_info['description'], ENT_QUOTES, 'UTF-8')) : '';
//            $price = $product_info['price'];
//
//            // 取主图
//            if (!empty($product_info['image'])) {
//                $image_url = HTTPS_CATALOG . 'image/' . $product_info['image'];
//            } else {
//                $image_url = ''; // 可设置默认图片
//            }
//
//            // 生成商品URL（OpenCart标准）
//            $link = HTTPS_CATALOG . 'index.php?route=product/product&product_id=' . $product_id;
//
//            // Google API商品对象
//            $product_obj = new \Google_Service_ShoppingContent_Product([
//                'offerId' => (string)$product_id,
//                'title' => $name,
//                'description' => $description,
//                'link' => $link,
//                'imageLink' => $image_url,
//                'contentLanguage' => 'zh',
//                'targetCountry' => 'CN',
//                'channel' => 'online',
//                'availability' => 'in stock',
//                'condition' => 'new',
//                'price' => [
//                    'value' => $price,
//                    'currency' => 'CNY'
//                ],
//                'brand' => 'YOUR_BRAND_NAME'
//            ]);
//
//            try {
//                $service->products->insert($merchantId, $product_obj);
//                $result_log[] = "上传成功：{$name}";
//            } catch (Exception $e) {
//                $result_log[] = "上传失败：{$name}，错误：" . $e->getMessage();
//            }
//        }
//
//        // 输出上传日志
//        $this->response->setOutput(implode("<br>", $result_log));
    }
}
